<?php
use PsiFramework\Classes\Util\Object\Image;

require_once("../../PsiFramework/Lib/psiframework.php");

if (array_key_exists('file', $_GET)) {
    $image = new Image();
    
    $imgPath = $_GET['file'];
    
    $width = 0;
    $height = 0;
    if (array_key_exists('width', $_GET) && array_key_exists('width', $_GET)) {
        $width = $_GET['width'];
        $height = $_GET['height'];
        if (!is_numeric($width) || !is_numeric($height)) {
            $width = 0;
            $height = 0;
        }
    }
    
    $external = false;
    
    if (startsWith($imgPath, 'http')) {
        $image->unserialize($imgPath);
        $realImage = $image->getImage();
        if (is_null($realImage) || $realImage == false) {
            $image->unserialize(getWwwDirectory().'/Images/Default/default_image.png');
        } else {
            $external = true;
        }
    } else {
    
        if (!startsWith($imgPath, '/')) {
            $imgPath = getWwwDirectory().'/'.$imgPath;
        }
        
        if (is_file($imgPath)) {
            $image->unserialize($imgPath);
        } else {
            $image->unserialize(getWwwDirectory().'/Images/Default/default_image.png');
        }
    }
    
    if ($width>0 && $height>0) {
        
        $miniaturePath = null;
        if (!$external) {
            $subDirectory = $width.'x'.$height;
            $newDir = $image->getFileDirectory().$subDirectory;
            if (!is_dir($newDir)) {
                mkdir($newDir);
            }
            $miniaturePath = $image->getFileLink($subDirectory);
        }
        
        if (is_null($miniaturePath) || !is_file($miniaturePath)) {
            $realImage = $image->createResizedPictures($miniaturePath, $width, $height, !$external);
            if ($external) {
                $image->display($realImage);
            }
        }
        
        if (is_file($miniaturePath)) {
            $image = new Image();
            $image->unserialize($miniaturePath);
        }
    }
    
    $image->display();
    exit;
}